const data = require('./data');

module.exports = {
    //select * from tb where func
    list(tb, func){
        var ret = [];
        var table = data[tb] || [];
        for(var k in table){
            var v = table[k];
            if(func && func(v))
                ret.push(v);
            else
                ret.push(v);
        }
        return ret;
    },

    get(tb, func){
        var table = data[tb] || [];
        for(var k in table){
            if(func && func(table[k]))
                return table[k];
        }
        return null;
    },

    add(tb, o){
        var table = data[tb] || [];
        var index = data.primary[tb] || 0;
        o.id = ++index;
        table.push(o);
        data[tb] = table;
        data.primary[tb] = o.id;
        return o;
    },

    update(tb, where, func){
        var count = 0;
        var table = data[tb] || [];
        for(var k in table){
            var v = table[k];
            if(where && !where(v))
                continue;

            if(func && func(v))
                count ++;
        }

        return count;
    },

    delete(tb, id){
        var table = data[tb];
        for(var k in table){
            var v = table[k];
            if(id == v.id){
                table.splice(k, 1);
                return true;
            }
        }
        return false;
    }
}